import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import purchaseApi from '@/api/purchase/purchase-api'
// import warehouseApi from '@/api/inwarehouse/warehouse-api'
import projectApi from '@/api/inwarehouse/project-api'
import goodsApi from '@/api/inwarehouse/goods-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import { exportExcel } from '@/utils/exprotExcel'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const statusOptions = [
      { value: '1', label: '新建' },
      { value: '99', label: '已完成' }
    ]


    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '采购单',
      api: purchaseApi,
      columns: [
        // { prop: 'serialId', label: '单号', valueType: 'input' },
        { prop: 'originalNo', label: '源单', valueType: 'slot', width: 200 },
        { prop: 'supplierName', label: '供应商', valueType: 'input' },
        { prop: 'planIncoming', label: '到货日期', slot: true, width: 150 },
        { prop: 'status', label: '状态', valueType: 'select', options: statusOptions, slot: true, width: 100 },
        { prop: 'operation', label: '操作', slot: true, width: 150 }
      ],
      rules: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
        date: [{ required: true, message: '请选择日期', trigger: 'change' }],
      },
      other: {
        formatDt(val: string) {
          if (!val) {
            return '-'
          }
          return val.substring(0, 10)
        },
        getStatusName(val: string) {
          const obj = statusOptions.find(item => {
            return item.value === val
          })
          if(obj) {
            return obj['label']
          }
          return val || '-'
        },
        handleProject(val: string) {
          const obj = data.projectOptions.find(item => {
            return item.id === val
          })
          ctx.editData.projectName = obj['name']
          ctx.editData.projectOriginalNo = obj['originalNo']
        },
        handleWarehouse(val: string) {
          const obj = data.warehouseOptions.find(item => {
            return item.id === val
          })
          ctx.editData.warehouseName = obj['name']
        },
        addGoods() {
          if (!ctx.editData['orderGoodsList']) {
            ctx.editData['orderGoodsList'] = []
          }
          ctx.editData['orderGoodsList'].push({})
        },
        delGoods() {
          data.delGoodsList.map(dgl => {
            const index = ctx.editData['orderGoodsList'].findIndex(item => {
              return item.id === dgl.id
            })
            ctx.editData['orderGoodsList'].splice(index, 1)
          })
        },
        handleGoodsSelectionChange(val: any) {
          if (!ctx.editData['orderGoodsList']) {
            return
          }
          data.delGoodsList = val
        },
        handleGoodsChange(val: string) {
          const index = ctx.editData['orderGoodsList'].findIndex(item => {
            return item.skuName === val
          })
          const obj = data.goodsOptions.find(gos => {
            return gos.skuName === val
          })
          const temp = JSON.parse(JSON.stringify(obj))
          ctx.editData['orderGoodsList'].splice(index, 1, temp)
        },
        export: () => {
          exportExcel({
            column: [
              { label: '物料编码', name: 'barCode' },
              { label: '物料名称', name: 'skuName' },
              { label: '规格型号', name: 'specification' },
              { label: '数量', name: 'number' },
            ], data: ctx.editData.orderGoodsList, filename: ctx.editData.supplierName + '-采购物料', autoWidth: true, format: 'xlsx'
          });
        }
      }
    }))

    // const getWarehouseList = async () => {
    //   const params = { filter: { disabled: false } }
    //   const res = await warehouseApi.list(params)
    //   data.warehouseOptions = res.data.records
    // }

    const getGoodsList = async (val: string) => {
      data.getGoodsLoading = true
      const params = { otherFilter: { skuName: val } }
      const res = await goodsApi.list(params)
      data.goodsOptions = res.data.records
      data.getGoodsLoading = false
    }

    const getProjectList = async () => {
      const params = { filter: { disabled: 2 } }
      const res = await projectApi.list(params)
      data.projectOptions = res.data.records
    }


    const data = reactive({
      ctx,
      statusOptions,
      warehouseOptions: [],
      goodsOptions: [],
      getGoodsLoading: false,
      delGoodsList: [],
      projectOptions: [],
      getGoodsList
    })

    // init
    onMounted(() => {
      // getWarehouseList()
      getGoodsList('')
      getProjectList()
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
